#include "EmblemCounter.h"
#include <QDebug>
#include "configure.cmake.h"

#ifdef CLICK_MODE
#include <QtDBus/QDBusConnection>
#include <QtDBus/QDBusMessage>
#include <QtDBus/QDBusPendingCall>
#include <QtDBus/QDBusPendingReply>

#define POSTAL_SERVICE "com.ubuntu.Postal"
#define POSTAL_PATH "/com/ubuntu/Postal"
#define POSTAL_IFACE "com.ubuntu.Postal"
#define PUSH_APP_ID "dekko.dekkoproject_dekko"
#define PKG_NAME "dekko.dekkoproject"
#else
#undef signals
extern "C"
{
    #include <unity/unity/unity.h>
    #include <gio/gio.h>
}
#define signals public
#define DESKTOP_ID "dekko.desktop"
#endif

namespace Launcher
{

EmblemCounter::EmblemCounter(QObject *parent) : QObject(parent),
    m_count(0)
{
#ifdef CLICK_MODE
    m_appId = QStringLiteral(PUSH_APP_ID);
    m_pkgname = QStringLiteral(PKG_NAME);
    m_pkgname = m_pkgname.replace(QStringLiteral("."), QStringLiteral("_2e"));
#endif
    connect(this, &EmblemCounter::countChanged, this, &EmblemCounter::updateLauncherCount);
}

int EmblemCounter::count() const
{
    return m_count;
}

void EmblemCounter::setCount(const int &count)
{
    if (count == m_count) {
        return;
    }
    m_count = count;
    emit countChanged(m_count);
}

void EmblemCounter::clear()
{
    setCount(0);
}

void EmblemCounter::updateLauncherCount()
{
    bool visible = m_count != 0;
#ifdef CLICK_MODE
    QDBusConnection bus = QDBusConnection::sessionBus();
    QString path(QStringLiteral(POSTAL_PATH));
    path += "/" + m_pkgname;
    QDBusMessage message = QDBusMessage::createMethodCall(QStringLiteral(POSTAL_SERVICE), path, QStringLiteral(POSTAL_IFACE), QStringLiteral("SetCounter"));
    message << m_appId << m_count << visible;
    QDBusPendingCall pcall = bus.asyncCall(message);
    QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(pcall, this);
    connect(watcher, &QDBusPendingCallWatcher::finished,
            [=](QDBusPendingCallWatcher *watcher){
        QDBusPendingReply<void> reply = *watcher;
        if (reply.isError()) {
            qDebug() << "Failed to set unread count:" << reply.error().message();
        }
        watcher->deleteLater();
    });
    // Because our mailbox watcher is timestamp based we may still
    // have notifications persisted from previous connections that
    // got marked read at some point but are not in MailboxWatcher::m_uids or MailboxWatcher::m_uidsWaiting
    // Since there is no unread messages there shouldn't be any persisted so
    // just remove them all.
//    if (count == 0) {
//        QStringList fakeList;
//        clearPersistentTags(fakeList);
//    }
#else
    qDebug() << "EmblemCounter::updateLauncherCount: Not implemented for Unity7 Launcher api";
    UnityLauncherEntry *entry = unity_launcher_entry_get_for_desktop_id(DESKTOP_ID);
    unity_launcher_entry_set_count(entry, (gint64)m_count);
    unity_launcher_entry_set_count_visible(entry, visible);
#endif
}

}
